#include <iostream>
#include "sockdist.h"
#include "sock.h"
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <string>

using namespace std;

#include "ServeurUDP.h"


ServeurUDP::ServeurUDP(){
}

ServeurUDP::ServeurUDP(int p,int t):Hote(p,t){
  // Demande de BR local

  Sock brPub(SOCK_DGRAM,(short)port,0);
  
  // On recupere le descripteur
  if(brPub.good()) {
    Hote::descBrLocale = brPub.getsDesc();
    cout << "# Demande de BR locale : OK" << endl;
  }
  else {
    cout << "Probleme BR Local" << endl;
    exit(1);
  }
  
  SockDist sexp("192.168.0.255",(short)Hote::port);
  adrBrDistante = sexp.getAdrDist();
  lgBrDistante = sexp.getsLen();

}
  

void ServeurUDP::envoyer(string t){
//envoie
  
 socklen_t lgBrInconnu = lgBrDistante;

 tamponSnd = conversionStringChar(t);

 int retourSend = sendto(Hote::descBrLocale,tamponSnd,tailleTampon,0,(sockaddr*)adrBrDistante,lgBrInconnu);
 
 if (retourSend == -1){
    perror("# sendTo");
    exit(EXIT_FAILURE);
  }
 else {
    cout<<"# message envoye"<<endl;
  }
}

string ServeurUDP::recevoir(){

  socklen_t lgBrInconnu = lgBrDistante;

  int retourRecv = recvfrom(Hote::descBrLocale,tamponRcv,Hote::tailleTampon,0,(sockaddr*)adrBrDistante,&lgBrDistante);
  if (retourRecv== -1){
    perror("# recvfrom ");
    exit(EXIT_FAILURE);
  }
  
  else{
    return conversionCharString(tamponRcv);
  }
  
  
}
